package com.kaka.bus.adapter;

import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.bean.QuestionBean;

import java.util.List;

/**
 * Created by zhangqi on 2017/12/25.
 * e-mail : ${email}
 * desc :
 */

public class QuestionAdapter extends BaseQuickAdapter<QuestionBean,BaseViewHolder> {

    public QuestionAdapter(int layoutResId, @Nullable List<QuestionBean> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, QuestionBean item) {

        boolean v = item.isOpen();
        if(v){
            helper.setImageResource(R.id.item_question_arraw,R.drawable.question_up);
        }else{
            helper.setImageResource(R.id.item_question_arraw,R.drawable.question_down);
        }
        helper.setVisible(R.id.item_question_rl,v);

        helper.setText(R.id.item_question_title,item.getQuestionText())
                .setText(R.id.item_question_answer,item.getAnswer());
        TextView title = helper.getView(R.id.item_question_title);
        helper.getView(R.id.item_question_title).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                View rl = helper.getView(R.id.item_question_rl);
                ViewGroup.MarginLayoutParams m = (ViewGroup.MarginLayoutParams) rl.getLayoutParams();
                if(title.getLineCount() >= 3){
                    m.topMargin = 0;
                }else{
                    m.topMargin = dpToPx(-10);

                }
                rl.setLayoutParams(m);
                title.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
            }
        });
    }

    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = AppCenter.getInstance().getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
}
